package com.baitengsoft.patentapimonitor.api.controller;

import com.baitengsoft.patentapimonitor.api.entity.LogUserinfoHistoryEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebPlatformEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebUserinfoEntity;
import com.baitengsoft.patentapimonitor.api.model.SearchPage;
import com.baitengsoft.patentapimonitor.api.service.LogUserinfoHistoryService;
import com.baitengsoft.patentapimonitor.api.service.WebPlatformService;
import com.baitengsoft.patentapimonitor.api.service.WebUserService;
import com.baitengsoft.patentapimonitor.api.service.WebUserTokenService;
import com.baitengsoft.patentapimonitor.common.utils.EncryptionStrategy;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author kenny
 */
@RestController
@RequestMapping("api/v1/web")
@Api(value = "前台-用户登录", description = "用户登录")
public class WebLoginController extends AbstractController {
    @Autowired
    private WebUserService webUserService;
    @Autowired
    private WebUserTokenService sysUserTokenService;
    @Autowired
    private WebPlatformService webPlatformService;

    @Autowired
    private LogUserinfoHistoryService logUserinfoHistoryService;

    /**
     * 登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(@RequestParam("userName") String username, @RequestParam("passWord") String password, HttpServletRequest request) throws IOException {
        //用户信息
        WebUserinfoEntity user = webUserService.queryByUserName(username);

        //账号不存在、密码错误
        if (user == null || !EncryptionStrategy.decrypt(user.getPwd()).equals(password)) {
            return Res.error("账号或密码不正确");
        }
        //账号锁定
        if (user.getStatus() != 1) {
            return Res.error("账号已被锁定,请联系管理员");
        }
        //生成token，并保存到数据库
        Res r = sysUserTokenService.createToken(user.getId());
        //日志记录
        logUserinfoHistoryService.saveLog(request, user);
        Integer platformid = user.getPlatformid();
        if (platformid != null) {
            r.put("platformId", user.getPlatformid());
            WebPlatformEntity platformEntity = webPlatformService.queryById(platformid);
            if (platformEntity != null)
                r.put("platformName", platformEntity.getName());
        }
        return r;
    }

    @Transactional
    @ApiOperation(value = "测试")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Res test(@RequestParam("id") int id) {
        getWebUserId();

        SearchPage param = new SearchPage();
        param.setPage(1);
        param.setPageSize(100);
        List<WebUserinfoEntity> list = webUserService.searchUserInfo(param).getItems();
        for (WebUserinfoEntity entity : list) {

            webUserService.editPassword(entity.getId(), entity.getPwd());
        }
        return Res.ok();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Res logout() {
        sysUserTokenService.logout(getWebUserId());
        return Res.ok();
    }

    @PostMapping(value = "/editPassword")
    public Res editPassword(@RequestParam("userName") String username, @RequestParam("oldPwd") String oldPwd, @RequestParam("newPwd") String newPwd) {
        //用户信息
        WebUserinfoEntity user = webUserService.queryByUserName(username);
        if (!user.getId().equals(getWebUserId())) {
            return Res.ok("参数有误，只可以修改本人密码");
        }
        if (!EncryptionStrategy.decrypt(user.getPwd()).equals(oldPwd)) {
            return Res.ok("原密码输入有误");
        }
        return webUserService.editPassword(getWebUserId(), newPwd);
    }

    @ApiOperation(value = "检查初始化数据，区域未设置返回code:420 AREA_UNINIT，指标未设置421 INDICATOR_UNINIT")
    @GetMapping(value = "/checkInit")
    public Res checkInit() {
        WebUserinfoEntity userInfo = getUserInfo();
        if (userInfo == null || userInfo.getPlatformid() == null) {
            return Res.error("用户信息获取失败");
        }
        return webPlatformService.checkInit(userInfo.getPlatformid());
    }
}
